﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Collections.ObjectModel;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Microsoft.Phone.BackgroundTransfer;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using MusicOnline.Resources;
using MyToolkit.Multimedia;
using System.ComponentModel;

namespace MusicOnline
{
    public partial class MainPage : PhoneApplicationPage
    {
        DownloadHelper download = new DownloadHelper();

        IsolatedStorageSettings localStorage = IsolatedStorageSettings.ApplicationSettings;

        List<VideoItem> listRecent = new List<VideoItem>();

        List<VideoItem> lsitem;
             // Constructor
        public MainPage()
        {
            InitializeComponent();

            Data.XmlHelper obj = new Data.XmlHelper();

            download.CreateFolderDownload();

            lsitem = obj.LoadList();

            this.DataContext = lsitem;

            List<AlphaKeyGroup<VideoItem>> Datasource=AlphaKeyGroup<VideoItem>.CreateGroups(lsitem,System.Threading.Thread.CurrentThread.CurrentUICulture,
                (VideoItem s) => { return s.Group; }, true);

            listMovie.ItemsSource = GetVideoItemGroup();

            LoadData();
            LoadListRecent();
        }

        private List<Group<VideoItem>> GetVideoItemGroup()
        {
            Data.XmlHelper obj = new Data.XmlHelper();
            IEnumerable< VideoItem > lsData= obj.LoadList();
            return GetItemGroups(lsData, v => v.Group);
            //download.CreateFolderDownload();
        }
        private static List<Group<T>> GetItemGroups<T>(IEnumerable<T> itemList, Func<T, string> getKeyFunc)
        {
            IEnumerable<Group<T>> groupList = from item in itemList
                                              group item by getKeyFunc(item) into g
                                              orderby g.Key
                                              select new Group<T>(g.Key, g);
            return groupList.ToList();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            
        }

        private async void Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            VideoItem item = (sender as Image).DataContext as VideoItem;

            //MessageBox.Show(item.Title);

            var url = await YouTube.GetVideoUriAsync(item.YoutubeID, YouTubeQuality.QualityMedium);

            if (url != null)
            {
                download.DownloadInApp(url.Uri, "tanthoi.mp4");

                NavigationService.Navigate(new Uri("/Download.xaml", UriKind.RelativeOrAbsolute));
            }
            else
                MessageBox.Show("Uri not found");   
        }

        private void LoadListRecent()
        {
            tileList.ItemsSource = null;

            List<TileItem> tileItems = new List<TileItem>();

            foreach (VideoItem item in listRecent)
            {
                tileItems.Add(new TileItem()
                    {
                        ImageUri = item.Image,
                       // Title =item.Title,
                        Notification = item.Title,
                        GroupTag = item.Group
                    });
            }
            tileList.ItemsSource = tileItems;
        }

        private void SaveData()
        {
            if (localStorage.Contains("DataRecent") == true)
            {
                localStorage["DataRecent"] = listRecent;
            }
            else

                localStorage.Add("DataRecent",listRecent);

            localStorage.Save();
        }
        private void LoadData()
        {
            if (localStorage.Contains("DataRecent") == true)
            {
                listRecent = localStorage["DataRecent"] as List<VideoItem>;
            }
        }
        protected async override void OnBackKeyPress(CancelEventArgs e)
        {
            if (YouTube.CancelPlay()) // used to abort current youtube download
                e.Cancel = true;
            else
            {
                // your code here
                var url = await YouTube.GetVideoUriAsync("Zln9I9IttLA", YouTubeQuality.Quality720P);
                if (url != null)
                {
                    MessageBox.Show(url.Uri.AbsolutePath);
                }
                else
                    MessageBox.Show("Uri not found");
            }
            base.OnBackKeyPress(e);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            YouTube.CancelPlay();

            base.OnNavigatedTo(e);
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            VideoItem selectedAlbum = (sender as MenuItem).DataContext as VideoItem;

            if (selectedAlbum != null)

                MessageBox.Show(selectedAlbum.YoutubeID);
        }

        private async void Image_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        {
            VideoItem item = (sender as Image).DataContext as VideoItem;

            if (item != null)
            {
                try
                {
                    await YouTube.PlayWithPageDeactivationAsync(
                        item.YoutubeID, true, YouTubeQuality.QualityHigh);

                    if (listRecent.Contains(item)==false)
                    {
                        if (listRecent.Count >= 8)
                        {
                            listRecent=listRecent.Skip(1).Take(7).ToList<VideoItem>();
                            listRecent.Add(item);
                        }
                        else
                            listRecent.Add(item);
                        LoadListRecent();
                        SaveData();
                    }
                }
                catch (Exception ex)
                {
                    SystemTray.ProgressIndicator.IsVisible = false;
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private async void HubTile_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
             TileItem item = (sender as HubTile).DataContext as TileItem;

             VideoItem videoItem = lsitem.Where(s => s.Title == item.Notification).First();

            if (videoItem != null)
            {
                try
                {
                    await YouTube.PlayWithPageDeactivationAsync(
                        videoItem.YoutubeID, true, YouTubeQuality.QualityHigh);
                }
                catch (Exception ex)
                {
                    SystemTray.ProgressIndicator.IsVisible = false;
                    MessageBox.Show(ex.Message);
                }
            }
        }

    }

    public class VideoItem
    {
        public string Group { set; get; }
        public string Image { set; get; }
        public string Title{set;get;}
        public string YoutubeID { set; get; }
        public string Author { set; get; }
    }
    public class TileItem
    {
        public string ImageUri
        {
            get;
            set;
        }

        public string Title
        {
            get;
            set;
        }

        public string Notification
        {
            get;
            set;
        }

        public bool DisplayNotification
        {
            get
            {
                return !string.IsNullOrEmpty(this.Notification);
            }
        }

        public string Message
        {
            get;
            set;
        }

        public string GroupTag
        {
            get;
            set;
        }
    }
}